/**
 * ------------------------------------------------------
 *  封装常用函数方法
 * ------------------------------------------------------
 *
 * Note: .
 *
 */

import { getToken } from "./token";


/**
* 验证文件格式及大小
* 验证通过返回true，否则返回错误信息
* @param {*} file 
* @returns string|bool
*/
export function verImage(file) {
    const isImage = file.type === 'image/jpeg' || file.type === 'image/png'
    if (!isImage) {
        return '请选择 JPG或PNG 格式的照片！'
    }
    const isLtSize = file.size / 1024 / 1024 < 2;
    if (!isLtSize) {
        return '图片超过大小限制，请控制在2MB以内！';
    }
    return isImage && isLtSize;
}


/**
 * 为上传添加请求头
 * @param {options} options 
 */
export function UploadRequest(options) {
    const xhr = new XMLHttpRequest();
    xhr.open('post', options.action, true);
    const token = getToken()
    xhr.setRequestHeader('Authorization', 'Bearer ' + token);
    const formData = new FormData();
    formData.append(options.filename, options.file);

    xhr.onload = () => {
        if (xhr.status === 200) {
        options.onSuccess(xhr.response, xhr);
        } else {
        options.onError(xhr.response, xhr);
        }
    };

    xhr.send(formData);
}

export function formDataToJSON(formData) {
    const jsonData = {};
    for (let [key, value] of Object.entries(formData)) {
        jsonData[key] = value;
    }
    console.log(jsonData)
    return JSON.stringify(jsonData)
  }

export function toQueryString(obj) {
    return Object.keys(obj).map(key => {
        let value = obj[key];
        if (Array.isArray(value)) {
            return value.map(arrayValue => encodeURIComponent(key) + '=' + encodeURIComponent(arrayValue)).join('&');
        }
        return encodeURIComponent(key) + '=' + encodeURIComponent(value);
    }).join('&');
}